package com.hdax.dmw.item.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SpringCacheConfig {
    private RedisCacheConfiguration getRedisConfigurationWithTtl(long seconds){
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                //默认SpringCache生成的key使用::分割，通过下面的方法进行重写改造
                .computePrefixWith(name->name+":")
                //键值序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                //不对null进行缓存
                .disableCachingNullValues()
                //设定缓存的过期时间
                .entryTtl(Duration.ofSeconds(seconds));
        return configuration;
    }

    //SpringCache全局配置管理器
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory) {
        //key表示 注解@Cacheable中的属性value/cacheNames的值
        Map<String,RedisCacheConfiguration> configurationMap = new HashMap<>();
        configurationMap.put("navs",getRedisConfigurationWithTtl(60L * 60 * 24));
        RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(connectionFactory)
                .withInitialCacheConfigurations(configurationMap)
                .build();
        return cacheManager;
    }

    //key最终的组成： cacheNames:自定义key
    //navs:index:navs
    @Bean
    public KeyGenerator keyGenerator(){
        return (target, method, params)->{
            StringBuilder builder = new StringBuilder();
            builder.append("index:navs");
            return builder.toString();
        };
    }
}
